package com.sg.framework.common.util;

import com.sg.framework.common.dto.BaseDto;
import com.sg.framework.common.dto.MetaDataDto;
import jakarta.validation.constraints.NotNull;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author ：CHS
 * @since 2022/6/9 10:58
 *
 *
 * @version 1.0
 */
public class MetaDataHelper {
    private static final Map<String, MetaDataDto> metaInfo = new ConcurrentHashMap<>();

    public static void putMetaData(Object obj) {
        String className = obj.getClass().getName();
        if (metaInfo.containsKey(className)) {
            return;
        }
        MetaDataDto metaData = new MetaDataDto();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        Field[] baseDeclareFields = BaseDto.class.getClass().getDeclaredFields();
        List<String> filteredList = new ArrayList<>();
        for (Field field : baseDeclareFields) {
            filteredList.add(field.getName());
        }

        for (Field field : declaredFields) {
            if (filteredList.contains(field.getName())) {
                continue;
            }
            field.setAccessible(true);
            NotNull flag = field.getAnnotation(NotNull.class);
            if (flag != null) {
                metaData.getRequiredFieldList().add(field);
            }
        }
        metaData.setAllRequired(declaredFields.length == metaData.getRequiredFieldList().size());
        metaInfo.put(className, metaData);
    }

    public static MetaDataDto getMetaData(Object obj) {
        String className = obj.getClass().getName();
        MetaDataDto retData = metaInfo.get(className);
        return retData;
    }
}
